package cc.angis.xiugallery;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.image.ui.ImageGridActivity;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageCache.ImageCacheParams;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.image.util.ThumbnailImageLoader;
import cc.angis.xiugallery.image.util.Utils;
import cc.angis.xiugallery.provider.IFolderSourceProvider;
import cc.angis.xiugallery.provider.SystemGalleryProvider;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class GroupingGridFragment extends SherlockFragment implements AdapterView.OnItemClickListener {
    private static final String TAG = "GroupingGridFragment";
    private static final String IMAGE_CACHE_DIR = "thumbs";
    private int mFolderThumbSize;
    private int mImageThumbSize;
    private int mFolderThumbSpacing;
    private GroupingAdapter mAdapter;
    protected IFolderSourceProvider mSourceProvider;
//    private Handler imageHandler;
    private ImageResizer mImageWorker;
    
    /**
     * Empty constructor as per the Fragment documentation
     */
    public GroupingGridFragment() {}
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_size);
        mFolderThumbSize = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_size);
        mFolderThumbSpacing = getResources().getDimensionPixelSize(R.dimen.folder_thumbnail_spacing);
        mSourceProvider = new SystemGalleryProvider(getActivity());
        mAdapter = new GroupingAdapter(getActivity());
        setHasOptionsMenu(true);
        ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);

        // Allocate a third of the per-app memory limit to the bitmap memory cache. This value
        // should be chosen carefully based on a number of factors. Refer to the corresponding
        // Android Training class for more discussion:
        // http://developer.android.com/training/displaying-bitmaps/
        // In this case, we aren't using memory for much else other than this activity and the
        // ImageDetailActivity so a third lets us keep all our sample image thumbnails in memory
        // at once.
        cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(getActivity()) / 3;

        // The ImageWorker takes care of loading images into our ImageView children asynchronously
        mImageWorker = new ThumbnailImageLoader(getActivity(), mImageThumbSize,Thumbnails.MICRO_KIND);
        mImageWorker.setAdapter(mSourceProvider);
        mImageWorker.setLoadingImage(R.drawable.empty_photo);
        mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(), cacheParams));
    }

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.group_grid_fragment, container, false);
        final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
        mSourceProvider.initSource();
        mGridView.setAdapter(mAdapter);
	    mGridView.setOnItemClickListener(GroupingGridFragment.this);
        // This listener is used to get the final width of the GridView and then calculate the
        // number of columns and the width of each column. The width of each column is variable
        // as the GridView has stretchMode=columnWidth. The column width is used to set the height
        // of each view so we get nice square thumbnails.
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (mAdapter.getNumColumns() == 0) {
                            final int numColumns = (int) Math.floor(
                                    mGridView.getWidth() / (mFolderThumbSize + mFolderThumbSpacing));
                            if (numColumns > 0) {
                                final int columnWidth =
                                        (mGridView.getWidth() / numColumns) - mFolderThumbSpacing;
                                mAdapter.setNumColumns(numColumns);
                                mAdapter.setItemHeight(columnWidth);
                                if (BuildConfig.DEBUG) {
                                    Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                                }
                            }
                        }
                    }
                });

        return v;
    }
    
    
    @Override
    public void onResume() {
        super.onResume();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        final Intent i = new Intent(getActivity(), ImageGridActivity.class);
        i.putExtra(GlobalConst.INTENT_BUCKET_ID,  mSourceProvider.getItem(position).toString());
        i.putExtra(GlobalConst.INTENT_GROUP_TYPE, GlobalConst.INTENT_GROUP_TYPE_GALLERY);
        i.putExtra(GlobalConst.INTENT_MENU_TYPE, GlobalConst.MenuType.MENU_TYPE_NONE);
        i.putExtra(GlobalConst.INTENT_BUCKET_NAME, mSourceProvider.getFolderList().get(position).getName());
        startActivity(i);
    }

    /**
     * The main adapter that backs the GridView. This is fairly standard except the number of
     * columns in the GridView is used to create a fake top row of empty views as we use a
     * transparent ActionBar and don't want the real top row of images to start off covered by it.
     */
    private class GroupingAdapter extends BaseAdapter {

        private final Context mContext;
        private int mItemHeight = 0;
        private int mNumColumns = 0;
        private int mActionBarHeight = -1;
        private GridView.LayoutParams mFolderViewLayoutParams;

        public GroupingAdapter(Context context) {
            super();
            mContext = context;
            mFolderViewLayoutParams = new GridView.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }

        @Override
        public int getCount() {
            // Size of adapter + number of columns for top empty row
            return mSourceProvider.getFolderList().size();
        }

        @Override
        public Object getItem(int position) {
        	return mSourceProvider.getItem(position);
        }

        @Override
        public long getItemId(int position) {
        	return position;
        }

        @Override
        public int getViewTypeCount() {
            // Two types of views, the normal ImageView and the top row of empty views
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
        	return 0;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup container) {
        	
        	 // First check if this is the top row
//            if (position < mNumColumns) {
//                if (convertView == null) {
//                    convertView = new View(mContext);
//                }
//                // Calculate ActionBar height
//                if (mActionBarHeight < 0) {
//                    TypedValue tv = new TypedValue();
//                    if (mContext.getTheme().resolveAttribute(
//                            com.actionbarsherlock.R.attr.actionBarSize, tv, true)) {
//                        mActionBarHeight = TypedValue.complexToDimensionPixelSize(
//                                tv.data, mContext.getResources().getDisplayMetrics());
//                    } else {
//                        // No ActionBar style (pre-Honeycomb or ActionBar not in theme)
//                        mActionBarHeight = 0;
//                    }
//                }
//                // Set empty view with height of ActionBar
//                convertView.setLayoutParams(new AbsListView.LayoutParams(
//                        ViewGroup.LayoutParams.MATCH_PARENT, mActionBarHeight));
//                return convertView;
//            }
//        	
            // Now handle the main ImageView thumbnails
            View view;
            
            ImageView imageView;
            TextView textView;
            if (convertView == null) { // if it's not recycled, instantiate and initialize
            	view = GroupingGridFragment.this.getLayoutInflater(getArguments()).inflate(R.layout.groupgrid, null);
            	view.setLayoutParams(mFolderViewLayoutParams);
            	
                imageView = (ImageView)view.findViewById(R.id.folderimages);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                
                textView = (TextView) view.findViewById(R.id.foldername);
            } else { // Otherwise re-use the converted view
            	view = convertView;
            	imageView = (ImageView)convertView.findViewById(R.id.folderimages);
            	textView = (TextView)convertView.findViewById(R.id.foldername);
            }

            // Check the height matches our calculated column width
            if (view.getLayoutParams().height != mItemHeight) {
            	view.setLayoutParams(mFolderViewLayoutParams);
            }

            // Finally load the image asynchronously into the ImageView, this also takes care of
            // setting a placeholder image while the background thread runs
            mImageWorker.loadText(position, textView);
            mImageWorker.loadImage(position, imageView);
            return view;
        }

        /**
         * Sets the item height. Useful for when we know the column width so the height can be set
         * to match.
         *
         * @param height
         */
        public void setItemHeight(int height) {
            if (height == mItemHeight) {
                return;
            }
            mItemHeight = height;
            mFolderViewLayoutParams =
                    new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
            mImageWorker.setImageSize(height);
            notifyDataSetChanged();
        }

        public void setNumColumns(int numColumns) {
            mNumColumns = numColumns;
        }

        public int getNumColumns() {
            return mNumColumns;
        }
    }

	@Override
	public void onDestroyView() {
		final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
//            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
////            Toast.makeText(getActivity(), R.string.clear_cache_complete,
////                    Toast.LENGTH_SHORT).show();
        }
		super.onDestroyView();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem menuItem = menu.add(Menu.NONE, GlobalConst.MENU_ID_SORT, 0, "Sort");
		menuItem.setIcon(R.drawable.ic_action_search);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch(item.getItemId()){
			case android.R.id.home:
				if (getActivity() instanceof SlidingFragmentActivity){
					((SlidingFragmentActivity)getActivity()).getSlidingMenu().showBehind();
				} else
					getActivity().finish();
				break;
			case GlobalConst.MENU_ID_SORT:
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
}

